package com.ly.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.ly.bean.EasybuySeckillGoods;
import com.ly.bean.EasybuySeckillOrder;
import com.ly.mapper.EasybuySeckillGoodsMapper;
import com.ly.mapper.EasybuySeckillOrderMapper;
import com.ly.service.SeckillOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;

/**
@author 李岩
@date 2021/12/14-13:52
@describe
*/
@Component
@Service(interfaceClass = SeckillOrderService.class)
public class SeckillOrderServiceImpl implements SeckillOrderService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private EasybuySeckillOrderMapper seckillOrderMapper;
    @Autowired
    private EasybuySeckillGoodsMapper seckillGoodsMapper;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        int count = 0;
        try {
            count = seckillOrderMapper.deleteByPrimaryKey(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }

    @Override
    public int insert(EasybuySeckillOrder record) {
        int count = 0;
        try {
            count = seckillOrderMapper.insert(record);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }

    @Override
    public int insertSelective(EasybuySeckillOrder record) {
        int count = 0;
        try {
            count = seckillOrderMapper.insertSelective(record);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }

    @Override
    public EasybuySeckillOrder selectByPrimaryKey(Integer id) {
        EasybuySeckillOrder easybuySeckillOrder = null;
        try {
            easybuySeckillOrder = seckillOrderMapper.selectByPrimaryKey(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return easybuySeckillOrder;
    }

    @Override
    public int updateByPrimaryKeySelective(EasybuySeckillOrder record) {
        int count = 0;
        try {
            System.out.println("updateByPrimaryKeySelective record="+record);
            count = seckillOrderMapper.updateByPrimaryKeySelective(record);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }

    @Override
    public int updateByPrimaryKey(EasybuySeckillOrder record) {
        int count = 0;
        try {
            count = seckillOrderMapper.updateByPrimaryKey(record);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }
    //添加抢购商品的订单信息
    @Override
    public String addKillOder(String userId, Integer seckillId) throws Exception {
        System.out.println("userId="+userId+"; seckillId= "+seckillId);
        String key=userId+"_"+seckillId;
        //判断商品是否已被该用户抢购且未支付
        EasybuySeckillOrder killOrder1 =(EasybuySeckillOrder) redisTemplate.boundHashOps("killUserOrder").get(key);
        if (killOrder1!=null){
            throw new Exception("该商品已被您抢购，且未支付");
        }
        //获取要购买的商品信息
        EasybuySeckillGoods killGood =(EasybuySeckillGoods) redisTemplate.boundHashOps("killGoods").get(seckillId + "");
        //如果商品为空 那么商品不存在
        if (killGood==null){
            throw new Exception("商品不存在");
        }
        //如果库存<=0  那就
        if (killGood.getStockCount()<=0){
            throw new Exception("商品已经抢购完了");
        }
        //在redis中更新库存
        killGood.setStockCount(killGood.getStockCount()-1);
        redisTemplate.boundHashOps("killGoods").put(seckillId+"",killGood);
        //如果商品已被秒杀完毕
        if (killGood.getStockCount()==0){
            //同步到数据库中
            seckillGoodsMapper.updateByPrimaryKeySelective(killGood);
            //从redis中删除秒杀商品
            redisTemplate.boundHashOps("killGoods").delete(seckillId);
        }
        EasybuySeckillOrder killOrder = new EasybuySeckillOrder();
        int oid = (int) System.currentTimeMillis();
        killOrder.setId(oid);
        killOrder.setStatus("0");
        killOrder.setMoney(BigDecimal.valueOf(killGood.getCostPrice()));
        killOrder.setCreateTime(new Date());
        killOrder.setSeckillId(Long.valueOf(seckillId));
        killOrder.setSellerId(killGood.getSellerId());
        killOrder.setUserId(userId);
        killOrder.setSeckillName(killGood.getTitle());
        System.out.println("秒杀商品订单 信息 "+killOrder);
        redisTemplate.boundHashOps("killUserOrder").put(key,killOrder);
        return killOrder.getId()+"";
    }
    //获取该用户的未支付秒杀订单列表信息
    @Override
    public List<EasybuySeckillOrder> findKillOrderFromRedisByUid(Integer userId) throws Exception {
        System.out.println("userId= "+userId);
        //从redis中获取用户的所有未支付的抢购订单列表  userid+"_"+goodid
        List<EasybuySeckillOrder> seckillOrderList = new ArrayList<>();
        Set<String> userGoodsKeySet =(Set<String>) redisTemplate.boundHashOps("killUserOrder").keys();
        for (String key : userGoodsKeySet) {
            System.out.println("key= "+key);
            //如果这个key 以当前用户的userid开头 那么就是这个用户的订单
            if (key.startsWith(userId+"")){
                seckillOrderList.add((EasybuySeckillOrder)redisTemplate.boundHashOps("killUserOrder").get(key));
            }
        }
        return seckillOrderList;
    }
    //通过抢购商品的订单id从redis中获取订单信息
    @Override
    public EasybuySeckillOrder findKillOrderFromRedisBySeckillId(Integer seckillId,Integer userId) throws Exception {
        String key=userId+"_"+seckillId;
        EasybuySeckillOrder killUserOrder =(EasybuySeckillOrder) redisTemplate.boundHashOps("killUserOrder").get(key);
        System.out.println("killUserOrder  "+killUserOrder);
        return killUserOrder;
    }
    //进入支付页面  然后把这个抢购的商品订单从redis中删除 然后再添加到MySQL中
    @Override
    public void addKillOrderToMysql(EasybuySeckillOrder seckillOrder, Integer userId) throws Exception {
        System.out.println("进入支付页面  seckillOrder="+seckillOrder+";userId="+userId);
        //从redis中删除订单信息
        redisTemplate.boundHashOps("killUserOrder").delete(userId+"_"+seckillOrder.getSeckillId());
        //把订单添加到数据库中
        seckillOrderMapper.insertSelective(seckillOrder);
    }
    //抢购商品的剩余支付时间为0 删除此订单
    @Override
    public void deleteKillOrderFromRedis(Integer goodId, Integer userId) throws Exception {
        String key=userId+"_"+goodId;
        //从redis中获取订单信息
        EasybuySeckillOrder killUserOrder =(EasybuySeckillOrder) redisTemplate.boundHashOps("killUserOrder").get(key);
        //如果订单为空则直接返回
        if (killUserOrder==null){
            return;
        }
        //获取当前订单对应的抢购商品对象
        EasybuySeckillGoods killGoods =(EasybuySeckillGoods) redisTemplate.boundHashOps("killGoods").get(goodId + "");
        //如果抢购商品为空 那么就是已经抢购完毕 更新到了数据库中，需要从数据库中获取添加到redis中
        if (killGoods==null){
            //从数据库查出来的抢购商品信息
            killGoods = seckillGoodsMapper.selectByPrimaryKey(goodId);
            killGoods.setStockCount(killGoods.getStockCount()+1);
            seckillGoodsMapper.updateByPrimaryKeySelective(killGoods);
        }else {
            killGoods.setStockCount(killGoods.getStockCount()+1);
        }
        //从redis中 删除订单 修改库存
        redisTemplate.boundHashOps("killUserOrder").delete(key);
        redisTemplate.boundHashOps("killGoods").put(goodId+"",killGoods);
    }

}
